#!/bin/bash
set -e

DURATION=${1:-10}          # 默认采样10秒
OUTPUT_FILE=${2:-oncpu}    # 默认输出文件名

check_deps() {
  if ! command -v perf &>/dev/null; then
    echo "错误: 请先安装 perf: sudo apt install linux-tools-$(uname -r)"
    exit 1
  fi
  if [ ! -d FlameGraph ]; then
    git clone --depth 1 https://github.com/brendangregg/FlameGraph.git || {
      echo "错误: 无法下载 FlameGraph"
      exit 1
    }
  fi
}

generate() {
  echo "采样中 (${DURATION}秒)..."
  perf record -F 99 -a -g -- sleep $DURATION
  perf script > perf-cpu.out
  FlameGraph/stackcollapse-perf.pl perf-cpu.out > folded.out
  FlameGraph/flamegraph.pl \
    --color=cpu \
    --title="On-CPU Flame Graph (${DURATION}s)" \
    --countname=samples \
    folded.out > "${OUTPUT_FILE}.svg"
  rm -f perf* *.out  # 可选清理
}

main() {
  #check_deps
  generate
  echo "生成成功: ${OUTPUT_FILE}.svg"
}

main "$@"